#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
#include "kernel/param.h"

int main(int argc, char *argv[])
{
    if (argc < 2)
    {
        fprintf(2, "Usage: xargs command missing\n");
        exit(1);
    }
    // 先保存xargs右边的参数，保存到args数组中
    char *args[MAXARG + 1];
    int index = 0;
    for (int i = 1; i < argc; ++i)
    {
        args[index++] = argv[i];
    }
    // 再从左边的输出转化得到的标准输入中添加参数
    char buf[1024];
    char *p = buf;
    while (read(0, p, 1) == 1)
    {
        // 管道可能有多行输出，对于每一行都要创建一个新进程
        if ((*p) == '\n')
        {
            *p = 0;
            int pid;
            if ((pid = fork()) == 0)
            {
                //子进程
                args[index] = buf;
                exec(argv[1], args);
                //如果执行失败了
                fprintf(2, "exec %s failed\n", argv[1]);
                exit(0);
            }
            else{
                //父进程
                wait(0);
                p = buf;
            }
            
        }
        else
        {
            ++p;
        }
    }

    exit(0);
}
